package com.x.linx.fenfencard.search;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import com.x.linx.fenfencard.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView.OnEditorActionListener;

public class SearchDemoActivity extends Activity {
	private static final String TAG = SearchDemoActivity.class.getName();
	private static final int SEARCH_BAR_HEIGHT = 40;
	private static final String strSearchHistoryFileName = "search_history";

	EditText edtSearch = null;
	ImageView imgSearchClear = null;
	ImageView imgSearch = null;
	ListView lstSearchHistory = null;
	File mAppFileDir = null;
	ArrayList<String> mSearchHistoryList = new ArrayList<String>();
	Button btnClearSearchHistory = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);

		mAppFileDir = getApplicationContext().getFilesDir();
		initUI();
	}

	private void initUI() {
		edtSearch = (EditText) findViewById(R.id.edtSearch);
		imgSearchClear = (ImageView) findViewById(R.id.imgSearchClear);
		imgSearch = (ImageView) findViewById(R.id.imgSearch);
		lstSearchHistory = (ListView) findViewById(R.id.lstSearchHistory);
		btnClearSearchHistory = (Button) findViewById(R.id.btnClearSearchHistory);
		
		edtSearch.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (TextUtils.isEmpty(edtSearch.getText().toString())) {
					imgSearchClear.setVisibility(View.INVISIBLE);
				} else {
					imgSearchClear.setVisibility(View.VISIBLE);
				}
			}
		});
		edtSearch.setOnEditorActionListener(new SearchEditActionListener());

		
		imgSearchClear.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				edtSearch.setText("");
				imgSearchClear.setVisibility(View.INVISIBLE);
			}
		});

		
		imgSearch.setOnClickListener(new SearchImageClickListener());

		initSearchBarHeight();

		loadSearchHistory();
		updateSearchHistory();
		lstSearchHistory
				.setOnItemClickListener(new SearchHistoryItemClickListener());

		btnClearSearchHistory.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mSearchHistoryList.clear();
				saveSearchHistory();
				updateSearchHistory();
			}
		});
	}

	private void loadSearchHistory() {
		File file = new File(mAppFileDir, strSearchHistoryFileName);
		if (file.exists()) {
			BufferedReader br = null;
			try {
				String s = null;
				br = new BufferedReader(new FileReader(file));
				mSearchHistoryList.clear();
				while (null != (s = br.readLine())) {
					mSearchHistoryList.add(s);
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (null != br) {
					try {
						br.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		} else {
			Log.i(TAG, "++++ loadSearchHistory(), " + file.getAbsoluteFile()
					+ " isn't exist.");
		}
	}

	private void saveSearchHistory() {
		File file = new File(mAppFileDir, strSearchHistoryFileName);
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter(file));
			for (int i = 0; i < mSearchHistoryList.size(); ++i) {
				bw.write(mSearchHistoryList.get(i));
				bw.newLine();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != bw) {
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private void updateSearchHistory() {
		lstSearchHistory.setAdapter(new ArrayAdapter<String>(
				SearchDemoActivity.this,
				android.R.layout.simple_expandable_list_item_1, mSearchHistoryList));
		if(mSearchHistoryList.size() > 0){
			btnClearSearchHistory.setVisibility(View.VISIBLE);
		}else{
			btnClearSearchHistory.setVisibility(View.GONE);
		}
	}

	private void initSearchBarHeight() {
		setViewRect(R.id.imgSearch, SEARCH_BAR_HEIGHT, SEARCH_BAR_HEIGHT);
		setViewRect(R.id.edtSearch, -1, SEARCH_BAR_HEIGHT);
		setViewRect(R.id.imgSearchClear, SEARCH_BAR_HEIGHT, SEARCH_BAR_HEIGHT);
	}

	private void setViewRect(int id, int width, int height) {
		View v = (View) findViewById(id);
		LayoutParams p = (LayoutParams) v.getLayoutParams();
		p.height = height;
		if (width > 0) {
			p.width = width;
		}
		v.setLayoutParams(p);
	}

	// //////////////////////////////////////////////////
	class SearchHistoryItemClickListener implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			String s = mSearchHistoryList.get(arg2);
			mSearchHistoryList.remove(arg2);
			edtSearch.setText(s);
			doSearch();
		}
	}

	class SearchImageClickListener implements OnClickListener {
		@SuppressLint("ShowToast")
		@Override
		public void onClick(View v) {
			doSearch();
		}
	}

	// handle search key in soft keyboard
	class SearchEditActionListener implements OnEditorActionListener {
		@Override
		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
			if (EditorInfo.IME_ACTION_SEARCH == actionId) {
				// 先隐藏键盘
				doSearch();
				return true;
			}
			return false;
		}
	}

	private void doSearch() {
		String s = edtSearch.getText().toString();
		if ("".equals(s)) {
			return;
		}
		// 先隐藏键盘
		((InputMethodManager) SearchDemoActivity.this
				.getSystemService(Context.INPUT_METHOD_SERVICE))
				.hideSoftInputFromWindow(SearchDemoActivity.this
						.getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
		imgSearchClear.setVisibility(View.INVISIBLE);
		edtSearch.setText("");
		mSearchHistoryList.add(0, s);
		saveSearchHistory();
		updateSearchHistory();
	}
}
